<template>
	<view class="container">
		<fu-navbar title="维保详情" bgColor="#0f68f0" color="#fff" isBackText></fu-navbar>
		<view class="tab-box">
			<view class="tab" :class="{'tab-active': current == 0}" @click="tabChange(0)">基本信息</view>
			<view class="tab" :class="{'tab-active': current == 1}" @click="tabChange(1)">备件</view>
			<view class="tab" :class="{'tab-active': current == 2}" @click="tabChange(2)">工作项</view>
		</view>
		<view style="margin-top: 90rpx;"></view>
		<view style="height: 44rpx;background-color: #f2f2f2;"></view>
		<block v-if="current == 0">
			<view class="bg-f padding-lr-24">
				<view class="flex align-center padding-tb-24 border-b-c9">
					<image src="../../../static/images/icon31.png" mode="widthFix" class="i-icon margin-r-24"></image>
					<text class="fs-32 text-bold">基本信息</text>
				</view>
				<view class="flex align-center justify-between padding-tb-24 border-b-c9 fs-28">
					<view>工单编号</view>
					<view>{{form.workOrderCode}}</view>
				</view>
				<view class="flex align-center justify-between padding-tb-24 border-b-c9 fs-28">
					<view>设备编号</view>
					<view>{{form.emCode}}</view>
				</view>
				<view class="flex align-center justify-between padding-tb-24 border-b-c9 fs-28">
					<view>设备名称</view>
					<view>{{form.emName}}</view>
				</view>
				<view class="flex align-center justify-between padding-tb-24 border-b-c9 fs-28">
					<view>位置</view>
					<view>{{form.emLocation}}</view>
				</view>
				<view class="flex align-center justify-between padding-tb-24 border-b-c9 fs-28">
					<view>维保时间</view>
					<view>{{form.upkeepStartTime}}</view>
				</view>
				<view class="flex align-center justify-between padding-tb-24 fs-28" :class="{'border-b-c9' : upkeepState == 7 }">
					<view>维保人</view>
					<view>{{mainInfo.employeeName}}</view>
				</view>
				<view v-if="upkeepState == 7" class="flex align-center justify-between padding-tb-24 fs-28" @click="toJumpTeam">
					<view>维保组成员：</view>
					<view>{{getMainTeamName}}</view>
				</view>
			</view>
			<block v-if="upkeepState == 2">
				<view style="height: 32rpx;background-color: #f2f2f2;"></view>
				<view class="bg-f padding-lr-24">
					<view class="flex align-center padding-tb-24 border-b-c9">
						<image src="../../../static/images/icon31.png" mode="widthFix" class="i-icon margin-r-24"></image>
						<text class="fs-32 text-bold">审核</text>
					</view>
					<view class="flex align-center justify-between padding-tb-24 fs-28 border-b-c9" @click="toggleTab('hour')">
						<view>预计工时</view>
						<view class="flex align-center">
							<view>{{estimatedWorkHour}}</view>
							<image src="../../../static/images/arrow-r.png" class="arrow-r"></image>
						</view>
					</view>
					<view class="flex padding-tb-24 fs-28">
						<view class="label">审核意见</view>
						<textarea placeholder="请输入内容" placeholder-class="pla-tar" class="tar" v-model="annExplain"></textarea>
					</view>
				</view>
			</block>
		</block>
		<block v-if="current == 1">
			<view class="bg-f padding-lr-24" style="border-radius: 16rpx 16rpx 0 0;">
				<view class="flex align-center padding-tb-24 border-b-c9">
					<image src="../../../static/images/icon32.png" mode="widthFix" class="b-icon margin-r-16"></image>
					<text class="fs-32 text-bold">维保备件</text>
				</view>
				<view class="flex align-center justify-between padding-tb-12" v-for="(item, index) in form.partList" :key="index">
					<view class="over-hidden">
						<view class="fs-28 text-ellipsis">{{item.name}}</view>
						<view class="fs-26 margin-t-18" style="color: #dcdcdc;">{{item.code}}</view>
					</view>
					<view class="flex align-center flex-shrink">
						<view class="flex align-center">
							<image src="../../../static/images/jian.png" class="jian" mode="aspectFill"></image>
							<view class="margin-lr-24 fs-28">{{item.partNum}}</view>
							<image src="../../../static/images/jia.png" class="jian" mode="aspectFill"></image>
						</view>
					</view>
				</view>
				<view class="no-data flex justify-center" v-if="form.partList&&form.partList.length == 0">
					<image src="../../../static/empty/no-data.png" class="img" mode="widthFix"></image>
				</view>
			</view>
		</block>
		<block v-if="current == 2">
			<view class="bg-f padding-lr-24" style="border-radius: 16rpx 16rpx 0 0;">
				<view class="flex align-center padding-tb-24 border-b-c9">
					<image src="../../../static/images/icon33.png" mode="widthFix" class="w-icon margin-r-16"></image>
					<text class="fs-32 text-bold">维保工作项</text>
				</view>
				<view class="flex align-center justify-between padding-tb-12 border-b-c9" v-for="(item, index) in form.taskList" :key="index">
					<view class="over-hidden">
						<view class="fs-28 text-ellipsis">{{item.taskName}}</view>
						<view class="fs-26 margin-t-18" style="color: #858585;">{{item.taskDesc}}</view>
						<view v-if="item.remark" class="fs-26 margin-t-18" style="color: #858585;">备注：{{item.remark}}</view>
					</view>
					<view class="flex-shrink flex align-center">
						<switch :checked="item.isComplete == 1 ? false : true" color="#04d919" @change="switchChange($event, index)" :disabled="upkeepState == 7 ? false : true"></switch>
					</view>
				</view>
			</view>
			<block v-if="upkeepState == 7 || upkeepState == 6 || upkeepState == 8 || upkeepState == 10 || upkeepState == 11 || upkeepState == 9">
				<!-- <view style="height: 32rpx;background-color: #f2f2f2;"></view> -->
				<view class="bg-f padding-lr-24">
					<view class="flex align-center padding-tb-24 border-b-c9">
						<image src="../../../static/images/icon34.png" mode="widthFix" class="i-icon margin-r-24"></image>
						<text class="fs-32 text-bold">维保信息</text>
					</view>
					<view class="flex padding-tb-24 fs-28">
						<view class="label flex-shrink">维保音频：</view>
						<view class="flex flex-wrap audio">
							<view class="flex align-center over-hidden padding-tb-12 over-hidden" @click="playAudio(item, index)" v-for="(item, index) in audioList" :key="index">
								<image src="../../../static/images/play.png" mode="aspectFill" class="play" v-if="!item.isPlay"></image>
								<image src="../../../static/images/stop.png" mode="aspectFill" class="play" v-else></image>
								<view class="audio-url text-ellipsis">{{item.fileName}}</view>
								<image src="../../../static/images/delete.png" mode="widthFix" style="width: 32rpx;" class="margin-l-24 flex-shrink" @click.stop="delFile(item, index, 'audio')"></image>
							</view>
							<view class="flex-shrink padding-lr-24"  @longtap="longpressBtn" @touchmove="handleTouchMove" @touchstart="longpressBtn" @touchend="touchendBtn($event, 'old')" @click="touchAudioBtn()" v-if="audioList.length < 9&&upkeepState==7">
								<image src="../../../static/images/icon27.png" mode="widthFix" style="width: 68rpx;"></image>
							</view>
						</view>
					</view>
					<view :class="longPress == '1' ? 'record-layer' : 'record-layer1'" @click="longPress = 1">
						<view :class="longPress == '1' ? 'record-box' : 'record-box1'">
							<view class="record-btn-layer">
								<button class="record-btn" :class="longPress == '1' ? '' : 'record-btn-2'"
									:style="VoiceTitle != '松开手指,取消发送' && longPress != '1'?'background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);':'background-color: rgba(0, 0, 0, 0);color:white'">
									<image src="../../../static/images/icon30.png" mode=""></image>
									<text>{{VoiceText}}</text>
								</button>
							</view>
							<!-- 语音音阶动画 -->
							<view
								:class="VoiceTitle != '松开手指,取消发送'?'prompt-layer prompt-layer-1':'prompt-layer1 prompt-layer-1'"
								v-if="longPress == '2'">
								<view class="prompt-loader">
									<view class="em" v-for="(item,index) in 15" :key="index"></view>
								</view>
								<text class="span">{{VoiceTitle}}</text>
							</view>
						</view>
					</view>
					<view class="flex padding-tb-24 fs-28">
						<view class="label flex-shrink"><text class="required-star">*</text>维保拍照：</view>
						<view class="imgs flex flex-wrap">
							<view class="img-wrap" v-for="(item, index) in imgList" :key="index">
								<image :src="`${read_url}${item.fileCode}`" class="img" mode="aspectFill"  @click="previewImg(item)"></image>
								<image src="../../../static/images/close.png" class="close" @click.stop="delFile(item, index, 'img')"></image>
							</view>
							<view class="img-wrap" v-if="imgList.length < 9&&upkeepState==7">
								<image src="../../../static/images/icon28.png" mode="widthFix" class="img" @click="uploadImg('img')"></image>
							</view>
						</view>
					</view>
					<view class="flex padding-tb-24 fs-28">
						<view class="label flex-shrink">维保视频：</view>
						<view class="imgs flex flex-wrap" v-for="(item, index) in videoList" :key="index">
							<view class="v-img" v-if="!item.isPlay" @click="playVideo(index)">
								<image src="" mode="aspectFill" lazy-load class="img"></image>
								<image class="v-play" src="../../../static/images/video-bg.png"></image>
								<image src="../../../static/images/close.png" class="close" @click.stop="delFile(item, index, 'video')"></image>
							</view>
							<view class="img-wrap" v-else>
								<video :src="`${read_url}${item.fileCode}`" class="img" :id="`myVideo${index}`" @fullscreenchange="fullscreenchange($event, index)" @ended="videoEnd($event, index)"></video>
							</view>
						</view>
						<view class="img-wrap" v-if="videoList.length < 9 &&upkeepState==7">
							<image src="../../../static/images/icon29.png" mode="widthFix" class="img" @click="uploadImg('video')"></image>
						</view>
					</view>
					<view class="flex padding-tb-24 fs-28">
						<view class="label">备注：</view>
						<textarea placeholder="请输入内容" placeholder-class="pla-tar" class="tar" v-model="remark"></textarea>
					</view>
				</view>
			</block>
		</block>
		<view class="bottom-wrap">
			<!-- 1,失效;2,待审核;3，待领取;4，待领取-拒单;5，待领取-转交；6，已分配;7,维修中;8,暂停;9,待指派验收人;10,待验收;11,验收通过 -->
			<view class="bottom justify-between" v-if="upkeepState == 2">
				<view class="btn left" @click="auditing(2)">撤销</view>
				<view class="btn right" @click="auditing(1)">审核</view>
			</view>
			<view class="bottom justify-center" v-if="upkeepState == 3&&state == 3">
				<view class="btn right" @click="receive(1)">领取</view>
			</view>
			<view class="bottom justify-center" v-if="upkeepState == 4 || (upkeepState == 3 && state == 4)">
				<view class="btn right" @click="zhipai">指派</view>
			</view>
			<view class="bottom justify-center" v-if="upkeepState == 9">
				<view class="btn right" @click="ysZhipai">验收指派</view>
			</view>
			<view class="bottom justify-between" v-if="upkeepState == 10">
				<view class="btn left" @click="accept(2)">验收驳回</view>
				<view class="btn right" @click="accept(1)">验收通过</view>
			</view>
			<view class="bottom justify-between" v-if="upkeepState == 8 || upkeepState == 6">
				<view class="btn left" @click="refuse">拒单</view>
				<view class="btn right" @click="startMain()" v-if="upkeepState == 6">开始维保</view>
				<view class="btn right" @click="suspend(2)" v-if="upkeepState == 8">继续</view>
			</view>
			<view class="bottom justify-between" v-if="upkeepState == 7">
				<view class="btn2 left" @click="suspend(1)">暂停</view>
				<view class="btn2 weixiu" @click="save()">保存</view>
				<view class="btn2 weixiu" @click="apply">申请维修</view>
				<view class="btn2 right" @click="submit">提交验收</view>
			</view>
		</view>
		
		<!-- 工作项 -->
		<w-picker mode="selector" :options="workState" themeColor="#30a3e0" :defaultProps="defaultProps" default-type="src" @confirm="onConfirm($event, 'selector')" ref="selector" :is-text="false" :is-img="true"></w-picker>
		
		<!-- 预计时长 -->
		<w-picker mode="selector" :options="hourList" themeColor="#30a3e0" @confirm="onConfirm($event, 'hour')" ref="hour" :value="estimatedWorkHour"></w-picker>
	</view>
</template>

<script>
import UploadImage from '@/common/utils/upload-image.js';
import {UPLOAD_IMAGE_URL, READ_FILE_URL} from '@/common/config.js';
import permission from "@/common/utils/authPermiss.js";
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = false;
export default {
	computed:{
		getMainTeamName () {
			return this.selectedItems.length ? this.selectedItems.map(item => item.employeeName).join(",") : ''
		}
	},
	data() {
		return {
			current: 0,
			isPlay: false,
			videoContext: null,
			workState: [
				{ src: '/static/images/dui.png', id: 1 },
				{ src: '/static/images/error.png', id: 2 }
			],
			defaultProps: {
				label: 'src'
			},
			workIndex: 0,
			upkeepState: 0,
			state: '',
			upkeepId: 0,
			form: {},
			annExplain: '',
			pid: 0,
			imgList: [],
			imgUploadList: [],
			videoList: [],
			// videoCodes: [],
			videoUploadList: [],
			read_url: READ_FILE_URL,
			mainInfo: {},
			audioList: [],
			audioUploadList: [],
			tartPoint: {}, //记录长按录音开始点信息,用于后面计算滑动距离。
			longPress: '1', // 1显示 按住 说话 2显示 说话中
			delShow: false, // 删除提示框显示隐藏
			time: 0, //录音时长
			duration: 60000, //录音最大值ms 60000/1分钟
			tempFilePath: '', //音频路径
			startPoint: {}, //记录长按录音开始点信息,用于后面计算滑动距离。
			sendLock: true, //发送锁，当为true时上锁，false时解锁发送
			VoiceTitle: '松手结束录音',
			VoiceText: '按住 说话',
			remark: '',
			estimatedWorkHour: '03:00',
			hourList: [],
			selectedItems: []
		}
	},
	onLoad(option) {
		this.upkeepId = option.upkeepId
		this.upkeepState = option.upkeepState
		this.state = option.state || ''
		this.init();
		uni.$on('getPerId', data => {
			this.pid = data.id
		})
	},
	onReady() {
		this.videoContext = uni.createVideoContext('myVideo');
	},
	mounted() {
	    uni.$on('refreshPreviousPage', (data) => {
	      this.handleReceivedData(data.data);
	    });
	},
	methods: {
		toJumpTeam(){
			uni.navigateTo({
				url: `/pages/service/select-per-more/index?orderId=${this.mainInfo.id}&type=repReceive&repStartTime=${this.form.upkeepStartTime}`,
				success:(res) => {
					res.eventChannel.emit('acceptData', { selectedItems: this.selectedItems }); 
				}
			})
		},
		handleReceivedData(selectedItems) {
			this.selectedItems = selectedItems;
		},
		init() {
			this.getDetail();
			this.getMaintenance();
			this.getHour();
		},
		getHour() {
			let arr = [];
			let timeArrays = new Array(48).fill(['', '']).map((item, index) => {
			    let startVal = index * 30;
			    let endVal = (index + 1) * 30;
			    let startHour = Math.floor((startVal / 60));
			    let startMinute = (startVal % 60);
			    let endHour = Math.floor((endVal / 60));
			    let endMinute = (endVal % 60);
			    let startTime = ((startHour < 10) ? ('0' + startHour) : startHour) + ':' + (startMinute === 0 ? '00' : startMinute);
			    let endTime = ((endHour < 10) ? ('0' + endHour) : endHour) + ':' + (endMinute === 0 ? '00' : endMinute);
				let obj = {
					label: endTime
				}
			    arr.push(obj)
			});
			this.hourList = arr
		},
		getDetail() {
			this.$api.post(global.apiUrls.getUpkeepBasisById, {
				upkeepId: this.upkeepId
			}).then(res => {
				if (res.data.code == 9100) {
					this.form = res.data.info
					this.upkeepState = res.data.info.upkeepState
					this.selectedItems = res.data.info.selectedItems || []
				} else {
					uni.showToast({
						title:res.data.msg,
						icon: 'none'
					})
				}
			})
		},
		// 查询维保信息
		getMaintenance() {
			this.$api.post(global.apiUrls.getMaintenanceUpkeepById, {
				upkeepId: this.upkeepId
			}).then(res => {
				if (res.data.code == 9100) {
					this.mainInfo = res.data.info
					this.remark = this.mainInfo.remark || ''
					this.imgList = []
					this.audioList = []
					this.videoList = []
					if (this.mainInfo.picNewList) {
						this.mainInfo.picNewList.forEach(item => {
							let obj = {
								fileCode: item.fileCode
							}
							this.imgList.push(obj)
						})
					}
					if (this.mainInfo.audioNewList) {
						this.mainInfo.audioNewList.forEach(res => {
							let obj = {
								url: `${READ_FILE_URL}${res.fileCode}`,
								isPlay: false,
								fileCode: res.fileCode,
								fileName: res.fileName
							}
							this.audioList.push(obj)
						})
					}
					if (this.mainInfo.videoNewList) {
						this.mainInfo.videoNewList.forEach(res => {
							let obj = {
								fileCode: res.fileCode,
								isPlay: false
							}
							this.videoList.push(obj)
						})
					}
				}
			})
		},
		tabChange(e) {
			this.current = e
		},
		playVideo(i) {
		  this.videoContext = uni.createVideoContext(`myVideo${i}`);
		  this.videoList[i].isPlay = true
		  let that = this;
		  setTimeout(() => {
		    that.videoContext.requestFullScreen(0);
		    that.videoContext.play();
		  }, 200);
		},
		fullscreenchange(e, i) {
			console.log(e);
			// 退出全屏时
			if (!e.detail.fullScreen) {
				this.videoList[i].isPlay = false;
				this.videoContext.pause();
			}
		},
		videoEnd(e, type) {
			this.videoContext.exitFullScreen();
			this.videoList[i].isPlay = false;
		},
		// 时间段转换分钟数
		timeToMin(timeStr) {
			let parts = timeStr.split(":")
			let hour = parseInt(parts[0], 10)
			let min = parseInt(parts[1], 10)
			return hour*60 + min
		},
		auditing(e) {
			let estimatedWorkHour;
			estimatedWorkHour = this.timeToMin(this.estimatedWorkHour)
			this.$api.post(global.apiUrls.insertAnnounceByUpkeep, {
				sourceId: this.form.upkeepId,
				annState: e,
				annExplain: this.annExplain,
				estimatedWorkHour: estimatedWorkHour
			}).then(res => {
				if (res.data.code == 9100) {
					uni.showToast({
						title: '操作成功',
						icon: 'none'
					})
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/tab/home/index'
						})
					}, 800)
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			})
		},
		toggleTab(ref, index) {
		  this.$refs[ref].show();
		  if (ref == 'selector') {
			  this.workIndex = index
		  }
		},
		onConfirm(e, type) {
			console.log(e)
			if (type == 'hour') {
				this.estimatedWorkHour = e.result
			}
		},
		switchChange(e, i) {
			console.log(e)
			if (e.detail.value) {
				this.form.taskList[i].isComplete = 2
			} else {
				this.form.taskList[i].isComplete = 1
			}
		},
		delFile(e, i, type) {
			if (type == 'audio') {
				this.audioList.splice(i, 1)
			} else if (type == 'img') {
				this.imgList.splice(i, 1)
			} else if (type == 'video') {
				this.videoList.splice(i, 1)
			}
			if (!e.isUpload) {
				this.$api.post(global.apiUrls.deleteFile, {
					fileCode: e.fileCode
				}).then(res => {
					if (res.data.code == 9100) {
						console.log(res)
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				})
			}
		},
		async checkRecord(e) {
		  try {
		    let checkResult = await permission("record");
		    console.log("检测信息：", checkResult);
		    if (checkResult.code == 1) {
		      let result = checkResult.data;
		      if (result == 1) {
		        console.log("授权成功!");
				let that = this
				if (this.isTouchEnd) return
				console.log(recorderManager)
				recorderManager.onStop((res) => {
					console.log(777);
					console.log(res);
					// that.userInfo.remark = res.tempFilePath;
				})
				console.log(555, recorderManager);
				that.startPoint = e.touches[0]; //记录长按时开始点信息，后面用于计算上划取消时手指滑动的距离。
				that.longPress = '2';
				that.VoiceText = '说话中...';
				const options = {
					// duration: that.duration, // 指定录音的时长，单位 ms
					// sampleRate: 16000, // 采样率
					numberOfChannels: 1, // 录音通道数
					// encodeBitRate: 96000, // 编码码率
					format: 'mp3', // 音频格式，有效值 aac/mp3
					frameSize: 10, // 指定帧大小，单位 KB
				}
				recorderManager.start(options);
				// 监听音频开始事件
				that.sendLock = false; //长按时是不上锁的。
				recorderManager.onStart((res) => {
					console.log(1111222)
				})
				// 	},
				// 	fail: (res) => {
				// 		uni.showToast({
				// 			title: '喊话失败',
				// 			icon: 'none'
				// 		})
				// 	}
				// })
		      }
		      if (result == 0) {
		        console.log("授权已拒绝!");
				uni.showToast({
					title: '麦克风权限未开启',
					icon: 'none'
				})
		      }
		      if (result == -1) {
		        console.log("您已永久拒绝麦克风权限，请在应用设置中手动打开!");
				uni.showToast({
					title: '您已永久拒绝麦克风权限，请在应用设置中手动打开!',
					icon: 'none'
				})
		      }
		    }
		  } catch (err) {
		    console.log("授权失败：", err);
		  }
		},
		// 语音开始
		longpressBtn(e) {
			this.isTouchEnd = false
			this.checkRecord(e);
		},
		handleTouchMove(e) {
			//touchmove时触发
			var moveLenght = e.touches[e.touches.length - 1].clientY - this.startPoint.clientY; //移动距离
			if (Math.abs(moveLenght) > 70) {
				// wx.showToast({
				//       title: "松开手指,取消发送",
				//       icon: "none",
				//       duration: 60000
				// });
				// console.log("松开手指,取消发送");
				this.VoiceTitle = "松开手指,取消发送";
				this.VoiceText = '松开手指,取消发送';
				this.delBtn()
				this.sendLock = true; //触发了上滑取消发送，上锁
			} else {
				// wx.showToast({
				//       title: "正在录音，上划取消发送",
				//       icon: "none",
				//       duration: 60000
				// });
				this.VoiceTitle = "松手结束录音";
				this.VoiceText = '松手结束录音';
				this.sendLock = false; //上划距离不足，依然可以发送，不上锁
			}
		},
		touchendBtn(e, type) {
			console.log('end', recorderManager)
			this.isTouchEnd = true
			this.longPress = '1';
			this.VoiceText = '按住 说话';
			this.VoiceTitle = '松手结束录音'
			recorderManager.onStop((res) => {
				console.log(this.sendLock);
				if (this.sendLock) {
					//上锁不发送
				} else { //解锁发送，发送网络请求
					if (res.duration < 1000)
						uni.showToast({
							title: "录音时间太短",
							icon: "none",
							duration: 1000
						});
					else {
						// this.userInfo.remark = res.tempFilePath
						console.log('end', res)
						let that = this
						uni.showLoading({
							mask: true,
							title: '上传中...'
						})
						uni.uploadFile({
							url: UPLOAD_IMAGE_URL,
							filePath: res.tempFilePath,
							fileType: 'audio',
							name: 'files',
							header: {
								'Authorization': global.token
							},
							formData: {
								'module': '',
								'dir': ''
							},
							success: (child) => {
								console.log(child)
								let data = JSON.parse(child.data);
								if (data.code == 9100) {
									// this.audio = data.info[0]
									const now = new Date();
									const year = now.getFullYear();
									const MM = `0${now.getMonth() + 1}`
									const month = MM.slice(-2)
									const dd = `0${now.getDate()}`
									const day = dd.slice(-2)
									const hh = `0${now.getHours()}`.slice(-2)
									const mm = `0${now.getMinutes()}`.slice(-2)
									const ss = `0${now.getSeconds()}`.slice(-2)
									let time = year + month + day + hh + mm + ss
									let path = `${READ_FILE_URL}${data.info[0]}`
									let obj = {
										url: path,
										isPlay: false,
										fileCode: data.info[0],
										fileName: time,
										isUpload: true
									}
									that.audioList.push(obj)
									// that.audioUploadList.push(obj)
								} else {}
							},
							complete: () => {
								uni.hideLoading()
							}
						});
					}
				}
			})
		
			// this.recordingTimer(this.time)
			recorderManager.stop(); //结束录音
		},
		touchAudioBtn() {
			
		},
		delBtn() {
			this.delShow = false;
			this.time = 0
			// this.VoiceTitle = '松手结束录音'
		},
		playAudio(item, i) {
			// this.isPlayAudio = !this.isPlayAudio
			this.audioList[i].isPlay = !this.audioList[i].isPlay
			innerAudioContext.src = `${READ_FILE_URL}${item.fileCode}`
			if (this.audioList[i].isPlay) {
				this.audioList.forEach((res, index) => {
					if (index !== i) {
						res.isPlay = false
					}
				})
				innerAudioContext.play();
			} else {
				this.audioList.forEach((res, index) => {
					res.isPlay = false
				})
				innerAudioContext.pause()
			}
			innerAudioContext.onEnded(() => {
				this.audioList[i].isPlay = false
			})
			// console.log(this.isPlayAudio,2)
		},
		// 领取
		receive(e) {
			this.$api.post(global.apiUrls.receiveUpkeep, {
				upkeepId: this.form.upkeepId,
				receiveType: e,
				employeeId: this.pid
			}).then(res => {
				if (res.data.code == 9100) {
					uni.showToast({
						title: '操作成功',
						icon: 'none'
					})
					setTimeout(() => {
						// uni.navigateBack()
						let title = '我处理的'
						let state = 6
						uni.redirectTo({
							url: `/pages/service/order/index?title=${title}&state=${state}`
						})
					}, 800)
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			})
		},
		zhipai() {
			uni.navigateTo({
				url: `/pages/service/select-per/index?orderId=${this.form.upkeepId}&type=upkeepReceive`
			})
		},
		ysZhipai() {
			uni.navigateTo({
				url: `/pages/service/select-per/index?orderId=${this.mainInfo.id}&type=upkeep`
			})
		},
		accept(e) {
			uni.navigateTo({
				url: `/pages/service/accept/index?type=${e}&title=维保验收&orderType=upkeep&orderId=${this.mainInfo.id}`
			})
		},
		refuse() {
			if (this.upkeepState == 6) {
				this.$api.post(global.apiUrls.refuseUpkeep, {
					id: this.mainInfo.id
				}).then(res => {
					if (res.data.code == 9100) {
						uni.showToast({
							title: '操作成功',
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 800)
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				})
			} else {
				this.$api.post(global.apiUrls.transferUpkeep, {
					id: this.mainInfo.id
				}).then(res => {
					if (res.data.code == 9100) {
						uni.showToast({
							title: '操作成功',
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 800)
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				})
			}
		},
		startMain() {
			this.$api.post(global.apiUrls.undeUpkeep, {
				id: this.mainInfo.id
			}).then(res => {
				if (res.data.code == 9100) {
					uni.showToast({
						title: '操作成功',
						icon: 'none'
					})
					this.init();
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			})
		},
		suspend(e) {
			this.$api.post(global.apiUrls.suspendUpkeep, {
				id: this.mainInfo.id,
				type: e //1暂停 2恢复
			}).then(res => {
				if (res.data.code == 9100) {
					uni.showToast({
						title: '操作成功',
						icon: 'none'
					})
					if (e == 1) {
						this.upkeepState = 8
					} else {
						this.upkeepState = 7
					}
					this.init();
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			})
		},
		save() {
			let taskList = []
			this.form.taskList.forEach(item => {
				let obj = {
					id: item.id,
					isComplete: item.isComplete
				}
				taskList.push(obj)
			})
			let picList = []
			let audioList = []
			let videoList = []
			this.imgList.forEach(item => {
				picList.push(item.fileCode)
			})
			this.audioList.forEach(item => {
				audioList.push(item.fileCode)
			})
			this.videoList.forEach(item => {
				videoList.push(item.fileCode)
			})
			this.$api.post(global.apiUrls.insertSuspendUpkeep, {
				id: this.mainInfo.id,
				fileNewPicCode: picList.join(','),
				fileNewVideoCode: videoList.join(','),
				fileNewAudioCode: audioList.join(','),
				taskList: JSON.stringify(taskList),
				remark: this.remark
			}).then(res => {
				if (res.data.code == 9100) {
					uni.showToast({
						title: '保存成功',
						icon: 'none'
					})
					
					return this.$api.post(global.apiUrls.getUpkeepBasisUpdateById,{
						upkeepId: this.form.upkeepId,
						maintenEmployeeUsersId: this.selectedItems.length ? this.selectedItems.map(item => item.id).join(',') : null, //维修组人员id
					}).then((res=>{
						if(res.data.code != 9100) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
						this.init();
					}))
					
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			})
		},
		apply() {
			setTimeout(() => {
				uni.navigateTo({
					url: `/pages/service/repair/index?info=${JSON.stringify(this.form)}&sourceType=1`
				})
			}, 800)
		},
		submit() {
			let that = this
			let taskList = []
			let isCofirm = true
			for(let i = 0;i < this.form.taskList.length; i++) {
				let item = this.form.taskList[i]
				if (item.isComplete == 1) {
					isCofirm=false
					break;
				}
			}
			if (!isCofirm) {
				uni.showToast({
					title: '存在未完成的工作项任务，无法提交验收',
					icon: 'none'
				})
				return
			}
			if (!this.imgList.length) {
				uni.showToast({
					title: '未上传工作项中维保拍照，无法提交验收',
					icon: 'none'
				})
				return
			}
			this.form.taskList.forEach(item => {
				let obj = {
					id: item.id,
					isComplete: item.isComplete
				}
				taskList.push(obj)
			})
			let picList = []
			let audioList = []
			let videoList = []
			this.imgList.forEach(item => {
				picList.push(item.fileCode)
			})
			this.audioList.forEach(item => {
				audioList.push(item.fileCode)
			})
			this.videoList.forEach(item => {
				videoList.push(item.fileCode)
			})
			this.$api.post(global.apiUrls.completeUpkeep, {
				id: that.mainInfo.id,
				fileNewPicCode: picList.join(','),
				fileNewVideoCode: videoList.join(','),
				fileNewAudioCode: audioList.join(','),
				taskList: JSON.stringify(taskList),
				remark: that.remark
			}).then(res => {
				if (res.data.code == 9100) {
					uni.showToast({
						title: '操作成功',
						icon: 'none'
					})
					
					return this.$api.post(global.apiUrls.getUpkeepBasisUpdateById,{
						upkeepId: this.form.upkeepId,
						maintenEmployeeUsersId: this.selectedItems.length ? this.selectedItems.map(item => item.id).join(',') : null, //维修组人员id
					}).then((res=>{
						if(res.data.code != 9100) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
						setTimeout(() => {
							uni.navigateBack()
						}, 800)
					}))
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
				}
			})
			// uni.showModal({
			// 	title: '提示',
			// 	content: '是否需要归还未使用完的备件？',
			// 	cancelColor: '#0099FF',
			// 	confirmColor: '#0099FF',
			// 	success: res => {
			// 		if (res.confirm) {
			// 			uni.navigateTo({
			// 				url: '/pages/spare-parts/inStorage/index'
			// 			})
			// 		} else if (res.cancel) {
						
			// 		}
			// 	}
			// })
		},
		select(item) {
			
		},
		previewImg(item) {
			uni.previewImage({
				urls: [`${READ_FILE_URL}${item}`]
			})
		},
		// 上传图片/视频
		uploadImg(type) {
			if (type == 'img') {
				uni.chooseImage({
					sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album", "camera"],
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						new UploadImage(tempFilePaths, {
							complete: (item) => {
								console.log(item, 'iiiiiiiii')
								item.forEach(data => {
									let obj = {
										fileCode: data,
										isUpload: true
									}
									this.imgList.push(obj)
									// this.imgUploadList.push(data)
								})
							}
						})
					}
				})
			} else if (type == 'video') {
				uni.chooseVideo({
					maxDuration: 60,
					count: 1,
					success: res => {
						uni.showLoading({
							title: '上传中...'
						});
						let videoFile = res.tempFilePath;
						let size = Math.ceil(res.size/1024/1024);
						if(size > 50 ) {
							uni.hideLoading();
							uni.showToast({
								title: '视频大小不能超过50M',
								icon: 'none'
							})
							return
						}
						this.uploadVideo(res)
					}
				})
			}
		},
		uploadVideo(file) {
			let _this = this
			// const aliyunFileKey = 'image/' + new Date().getTime() + Math.floor(Math.random() * 150) + '.mp4';
			uni.uploadFile({
				url: UPLOAD_IMAGE_URL,
				files: [{
					name: 'files',
					file: file.tempFile,
					uri: file.tempFilePath
				}],
				// name: 'file',
				fileType: 'video',
				header: {
				  'Authorization': global.token || ''
				  // "Content-Type": "multipart/form-data"
				},
				// formData: {
				// 	'files': file.tempFile
				// },
				success: res => {
					console.log(res, 'resres')
					let data = JSON.parse(res.data)
					if (data.code == 9100) {
						uni.hideLoading();
						// let fileData = {}
						let info = data.info
						info.forEach(item => {
							// _this.videoCodes.push(item)
							_this.videoUploadList.push(item)
							let obj = {
								fileCode: item,
								isPlay: false,
								isUpload: true
							}
							_this.videoList.push(obj)
						})
					} else {
					  uni.hideLoading();
					  uni.showToast({
					  	title: '上传失败，请重试',
						icon: 'none'
					  })
					}
				},
				complete: () => {
				  setTimeout(function () {
					  uni.hideLoading();
				  }, 1000);
				}
			})
		},
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: #f3f5f8;
}
.tab-box {
	position: fixed;
	width: 100%;
	top: 150rpx;
	background-color: #fff;
	display: flex;
	align-items: center;
	height: 100rpx;
	z-index: 99;
	.tab {
		flex: 1;
		text-align: center;
		line-height: 100rpx;
		color: #7f7f7f;
		position: relative;
	}
	.tab-active {
		color: #333;
		&::after {
			content: '';
			position: absolute;
			width: 90rpx;
			height: 6rpx;
			background-color: #555;
			border-radius: 2rpx;
			bottom: 0;
			left: 0;
			right: 0;
			margin: 0 auto;
		}
	}
}
.i-icon {
	width: 40rpx;
}
.label {
	width: 180rpx;
	// text-align: right;
}
.audio {
	.play {
		width: 32rpx;
		height: 32rpx;
		flex-shrink: 0;
		margin-right: 12rpx;
	}
	.audio-url {
		color: #6c8bb6;
		text-decoration: underline;
	}
}
.img-wrap {
		position: relative;
		margin-right: 16rpx;
		margin-bottom: 12rpx;
		.img {
			width: 120rpx;
			height: 120rpx;
		}
		.close {
			width: 32rpx;
			height: 32rpx;
			position: absolute;
			z-index: 9;
			top: -8rpx;
			right: -8rpx;
		}
	}
	.v-img {
		width: 120rpx;
		height: 120rpx;
		margin-right: 12rpx;
		margin-bottom: 12rpx;
		position: relative;
		.close {
			width: 32rpx;
			height: 32rpx;
			position: absolute;
			z-index: 9;
			top: -8rpx;
			right: -8rpx;
		}
		.img {
			width: 100%;
			height: 100%;
			background-color: #000;
		}
		.v-play {
			position: absolute;
			width: 44rpx;
			height: 44rpx;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			margin: auto;
		}
	}

.pla-tar {
	color: #c3c3c3;
}
.tar {
	height: 180rpx;
	border: 1rpx solid #c3c3c3;
	border-radius: 16rpx;
	padding: 12rpx;
	font-size: 28rpx;
}
.b-icon {
	width: 60rpx;
}
.w-icon {
	width: 48rpx;
}
.jian {
	width: 32rpx;
	height: 32rpx;
}
.no-data {
	min-height: 300rpx;
	.img {
		width: 160rpx;
		margin-top: 32rpx;
	}
}
.select-icon {
	width: 60rpx;
	height: 60rpx;
}
.arrow-r {
	width: 32rpx;
	height: 32rpx;
	margin-left: 8rpx;
}
.bottom-wrap {
	height: 140rpx;
	.bottom {
		padding: 24rpx 32rpx;
		position: fixed;
		bottom: 0;
		height: 140rpx;
		box-sizing: border-box;
		display: flex;
		width: 100%;
		z-index: 99;
		.btn {
			width: 256rpx;
			height: 80rpx;
			border-radius: 10rpx;
			text-align: center;
			line-height: 80rpx;
			color: #fff;
			font-size: 34rpx;
		}
		.btn2 {
			width: 23%;
			height: 80rpx;
			border-radius: 10rpx;
			text-align: center;
			line-height: 80rpx;
			color: #fff;
			font-size: 34rpx;
		}
		.left {
			background-color: #d9001b;
		}
		.right {
			background-color: #0f68f0;
		}
		.lingqu {
			background-color: #f85d76;
		}
		.weixiu {
			background-color: rgba(24, 191, 67, 1);
		}
	}
}

.required-star {
  color: red; 
  font-size: 36rpx; 
  margin-right: 8rpx; 
}

</style>